//路由守卫
import router from '@/router/index'
import store from "@/store/index";
// 页面刷新时，重新赋值token
if (localStorage.getItem('Authorization')) {
    store.commit('SET_TOKEN', localStorage.getItem('Authorization'))
}
if (localStorage.getItem('menuList')) {
    store.commit('SET_MENU_LIST', JSON.parse(localStorage.getItem('menuList') + ''))
}
if (localStorage.getItem('userInfo')) {
    store.commit('SET_USER_INFO', JSON.parse(localStorage.getItem('userInfo') + ''))
}


router.beforeEach((to, from, next) => {
    const whiteList = ['/login'] // 白名单
    const token = store.getters.GET_TOKEN;
    const hasRoutes = store.state.hasRoutes;
    const menuList = store.getters.GET_MENU_LIST;
    if (token) {
        if (!hasRoutes) {
            bindRoute(menuList);
            store.commit("SET_ROUTES_STATE", true);
            next({ ...to, replace: true })
        }
        next();
    } else {
        if (whiteList.includes(to.path)) {
            next();
        } else {
            next("/login");
        }
    }
})
//动态绑定路由
const bindRoute = (menuList: any) => {
    console.log(menuList)
    const newRoutes = router.options.routes;
    menuList.forEach((menu: any) => {
        if (menu.children) {
            menu.children.forEach((m: any) => {
                //菜单转成路由
                const route = menuToRoute(m, menu.name);
                if (route) {
                    newRoutes[0].children?.push(route)//添加到路由管理
                }

            })
        }
    })
    // 重新添加到路由
    newRoutes.forEach((route: any) => {
        router.addRoute(route);
    })
    console.log('router123', router.options.routes)

}

const menuToRoute = (menu: any, parentName: any) => {
    if (!menu.component) {
        return null;
    } else {
        const route: any = {
            name: menu.name,
            path: menu.path,
            meta: {
                parentName: parentName
            }
        }
        route.component = () => import('@/views/' + menu.component + '.vue')
        return route

    }


}